package org.mozhu.mboot.core.web.freemarker;

import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.mozhu.mboot.core.config.ApplicationConfiguration;
import org.mozhu.mboot.core.file.util.PathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import java.util.Map;

/**
 * 将常用的静态工具类暴露到freemarker里使用
 */
@Configuration
@Slf4j
@Import(FreeMarkerSecurityAutoConfiguration.class)
public class FreeMarkerMVCAutoConfiguration {

    @Autowired
    public void freeMarkerConfigurer(FreeMarkerConfigurer configurer, ApplicationConfiguration applicationConfiguration) {
        try {
            configurer.getConfiguration().setClassicCompatible(true);
            configurer.getConfiguration().setSharedVariable("applicationConfiguration", applicationConfiguration);
        } catch (TemplateModelException e) {
            log.error("set shared variable for freemarker failed", e);
        }
    }

    @Bean
    @ConditionalOnMissingBean
    public FreeMarkerStaticModelRegistry freeMarkerStaticModelRegistry(FreeMarkerViewResolver freeMarkerViewResolver) {
        FreeMarkerStaticModelRegistry freeMarkerStaticModelRegistry = new FreeMarkerStaticModelRegistry();
        freeMarkerStaticModelRegistry.register(StringUtils.class);
        freeMarkerStaticModelRegistry.register(CollectionUtils.class);
        freeMarkerStaticModelRegistry.register(DateFormatUtils.class);
        freeMarkerStaticModelRegistry.register(PathUtils.class);
        Map<String, Object> attributesMap = freeMarkerStaticModelRegistry.getStaticModels();
        freeMarkerViewResolver.setAttributesMap(attributesMap);
        return freeMarkerStaticModelRegistry;
    }

    @Bean
    public FreemarkerControllerAdvice freemarkerControllerAdvice() {
        return new FreemarkerControllerAdvice();
    }

}
